package off_imp

import (
	sqlc "bp/db/sqlc"
	"bp/internal/render"
	sharedVld "bp/internal/rpcserver/shared/vld"
	"bp/internal/service/com/offer"
	"bp/internal/util"
	offGrpc "bp/rpc/gen/backendapi/off"
	"context"
)

// ValidateTransactItem offGrpc.TransactOrderItemEntity
func ValidateTransactItem(v *offGrpc.TransactOrderItemEntity) (err error) {
	if v.DetailId < 0 {
		err = render.InvalidArgumentRange("item.detail_id")
		return
	}
	if v.DetailCnt <= 0 {
		err = render.InvalidArgumentRange("item.detail_cnt")
		return
	}
	if v.ItemId < 0 {
		err = render.InvalidArgumentRange("item.item_id")
		return
	}
	if v.ItemSpecId < 0 {
		err = render.InvalidArgumentRange("item.item_spec_id")
		return
	}
	if v.ItemPrice < 0 {
		err = render.InvalidArgumentRange("item.item_price")
		return
	}
	return
}

// ValidateTransactOrder offGrpc.TransactOrderEntity
func ValidateTransactOrder(v *offGrpc.TransactOrderEntity) (err error) {
	if v.OwnerId < 0 {
		err = render.InvalidArgumentRange("order.owner_id")
		return
	}
	if util.IsEmpty(v.OutOrderNo) {
		err = render.InvalidArgumentRange("order.out_order_no")
		return
	}
	for _, it := range v.Items {
		err = ValidateTransactItem(it)
		if err != nil {
			return
		}
	}
	return
}

// VldTransactLockReq 验证交易锁定请求
func (s *OffBackendApiImp) VldLockTransactionReq(ctx context.Context, q *sqlc.Queries, req *offGrpc.LockTransactionReq) (toLockTransactOrderPtrs []*offer.ToLockTransactOrder, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	if req.BrandId < 0 {
		err = render.InvalidArgumentRange("brand_id")
		return
	}
	if req.MemberId < 0 {
		err = render.InvalidArgumentRange("member_id")
		return
	}
	if util.IsEmpty(req.OutTransNo) {
		err = render.InvalidArgumentRange("out_trans_no")
		return
	}
	if !sharedVld.IsOfferUseScene(req.TransactScene) {
		err = render.InvalidArgumentRange("transact_scene")
		return
	}
	if len(req.Orders) == 0 {
		err = render.InvalidArgumentRange("orders")
		return
	}
	for _, order := range req.Orders {
		err = ValidateTransactOrder(order)
		if err != nil {
			return
		}
		toLockTransactOrderPtrs = append(toLockTransactOrderPtrs, s.ConvTransactOrderPtrPbToEntity()(order))
	}

	slog.Infof("off_trial_imp/cmd_vld.VldLockTransactionReq ok")
	return
}
